package db

import (
	"cloud-disk/global/define"
	"fmt"
	"github.com/gomodule/redigo/redis"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"log"
	"time"
)

var db *gorm.DB
var rdb *redis.Pool

func InitDB() {
	InitMysql()
	InitRedis()
}

func InitRedis() {
	redisConf := define.Conf.Redis
	rdb = &redis.Pool{
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", ":"+redisConf.Port)
			if err != nil {
				log.Fatalln("redis init fail")
				return nil, err
			}
			if _, err := c.Do("AUTH", redisConf.Password); err != nil {
				c.Close()
				log.Fatalln("redis auth fail")
				return nil, err
			}
			return c, nil
		},
		TestOnBorrow: func(c redis.Conn, t time.Time) error {
			if time.Since(t) < time.Minute {
				return nil
			}
			_, err := c.Do("PING")
			return err
		},
		MaxIdle:   300,
		MaxActive: 30,
	}
}
func InitMysql() {
	fmt.Println(define.Conf)
	c := define.Conf.MySQL
	dsn := c.Username + ":" + c.Password + "@tcp(" + c.Host + ":" + c.Port + ")/" + c.DBName + "?" + c.Url
	fmt.Println(dsn)
	open, err := gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
		return
	}
	db = open
}
func DB() *gorm.DB {
	return db
}
func RDB() *redis.Pool {
	return rdb
}
